<template>
  <div class="create-post-page">
    <div class="content-wrapper">
      <el-card class="form-card">
        <template #header>
          <div class="card-header">
            <h2>发布帖子</h2>
          </div>
        </template>

        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="80px"
          @submit.prevent
        >
          <el-form-item label="标题" prop="title">
            <el-input v-model="form.title" placeholder="请输入标题" />
          </el-form-item>

          <el-form-item label="内容" prop="content">
            <el-input
              v-model="form.content"
              type="textarea"
              :rows="8"
              placeholder="请输入内容"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSubmit" :loading="submitting">
              发布
            </el-button>
            <el-button @click="$router.back()">取消</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'

const router = useRouter()
const formRef = ref(null)
const submitting = ref(false)

const form = ref({
  title: '',
  content: ''
})

const rules = {
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { min: 2, max: 100, message: '标题长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入内容', trigger: 'blur' },
    { min: 10, max: 10000, message: '内容长度在 10 到 10000 个字符', trigger: 'blur' }
  ]
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    const res = await request.post('/api/forum/posts', form.value)
    if (res.code === 200) {
      ElMessage.success('发布成功')
      router.push('/front/forum')
    }
  } catch (error) {
    if (error?.message !== 'validate failed') {
      console.error('发布帖子失败:', error)
      ElMessage.error(error.response?.data?.message || '发布失败')
    }
  } finally {
    submitting.value = false
  }
}
</script>

<style lang="scss" scoped>
.create-post-page {
  .content-wrapper {
    max-width: 800px;
    margin: 0 auto;
    padding: 20px;
  }

  .form-card {
    .card-header {
      h2 {
        margin: 0;
        font-size: 20px;
        color: #303133;
      }
    }
  }
}
</style> 